﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleDatabaseAdapter
{
    public class SimpleDataAdapter : ISimpleDataAdapter
    {
        public static SimpleDataAdapter Current
        {
            get
            {
                return _Instance;
            }
        }
        private static SimpleDataAdapter _Instance;

        public static SimpleDataAdapter CreateInstance(string connectionString)
        {
            _Instance = new SimpleDataAdapter(connectionString);
            return _Instance;
        }
        public static SimpleDataAdapter CreateInstance(string connectionString, string tableListsName, string tableAllDataName)
        {
            _Instance = new SimpleDataAdapter(connectionString, tableListsName, tableAllDataName);
            return _Instance;
        }

        public SimpleDataAdapter(string connectionString)
            : this(connectionString, String.Empty, String.Empty)
        {
        }
        public SimpleDataAdapter(string connectionString, string tableListsName, string tableAllDataName)
        {
            Init(connectionString, tableListsName, tableAllDataName);
        }

        private void Init(string connectionString, string tableListsName, string tableAllDataName)
        {
            SetupConfigData(connectionString, tableListsName, tableAllDataName);
            SetupTables();
            CheckDataBase(Config);
        }

        private void SetupConfigData(string connectionString, string tableListsName, string tableAllDataName)
        {
            Config = new SimpleDataAdapterConfig();
            Config.SQLConnectionString = connectionString;
            if (!string.IsNullOrEmpty(tableListsName)) Config.TableListsName = tableListsName;
            if (!string.IsNullOrEmpty(tableAllDataName)) Config.TableAllDataName = tableAllDataName;
        }
        private void SetupTables()
        {
            TableCreator = new TableCreator(this);
            Lists = new Lists(this);
            AllData = new AllData(this);
        }
        private void CheckDataBase(SimpleDataAdapterConfig config)
        {
            DatabaseAccess = new DatabaseAccess(config.SQLConnectionString);
        }

        internal SimpleDataAdapterConfig Config { get; private set; }
        internal DatabaseAccess DatabaseAccess { get; private set; }
        internal TableCreator TableCreator { get; private set; }
        public ILists Lists { get; private set; }
        public IAllData AllData { get; private set; }
    }
}
